package com.cooldatasoft.web.cms.login;

import org.apache.wicket.Application;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Session;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;

import com.cooldatasoft.app.WOCApplication;
import com.cooldatasoft.app.WOCSession;
import com.cooldatasoft.base.BasePage;
import com.cooldatasoft.data.User;
import com.cooldatasoft.web.cms.main.AdminOrganizationChart;

public class LoginPage extends BasePage {

	public LoginPage(){
		LoginForm loginForm = new LoginForm("loginForm");
		add(loginForm);
	}
	
	class LoginForm extends Form {

		private User user;
		
		private FeedbackPanel feedbackPanel;
		private Label usernameLabel;
		private Label passwordLabel;
		private RequiredTextField username;
		private PasswordTextField password;
		private Button loginButton;
		
		public LoginForm(String id) {
			super(id);
			user = new User();
			
			feedbackPanel = new FeedbackPanel("feedbackPanel"); 
			usernameLabel = new Label("usernameLabel",new StringResourceModel("usernameLabel.value.username",new Model()));
			passwordLabel = new Label("passwordLabel",new StringResourceModel("passwordLabel.value.password",new Model()));
			
			username = new RequiredTextField("username",new PropertyModel(this,"user.username"));
			password = new PasswordTextField("password",new PropertyModel(this,"user.password"));
			loginButton = new Button("loginButton");

			AttributeModifier loginButtonValueAttributeModifier =
				new AttributeModifier("value",new StringResourceModel("loginButton.value.login",new Model()));
			loginButton.add(loginButtonValueAttributeModifier);
			
			add(username);
			add(password);
			add(usernameLabel);
			add(passwordLabel);
			add(loginButton);
			add(feedbackPanel);
		}
		
		@Override
		protected void onSubmit() {
			user.setPassword("admin");
			user.setUsername("admin");
			setUser(((WOCApplication) Application.get()).getUserServiceProxy().authenticate(getUser()));
			if(getUser()!=null){
				((WOCSession)Session.get()).setUser(getUser());
				
//				PageParameters param = new PageParameters();
//				param.put("personId", new Integer(17));
//				setResponsePage(new PersonPage(param));
				setRedirect(true);
				setResponsePage(AdminOrganizationChart.class);
			}else{
				feedbackPanel.error("Incorrect username or password!");
			}
		}


		public User getUser() {
			return user;
		}
		public void setUser(User user) {
			this.user = user;
		}		
	}
}
